package com.mdd.common.util;

/**
 * @author yangzhengyin
 * @date 2025/10/16
 */
public class AddressUtil {

    /**
     * 计算两个经纬度之间的距离，并格式化输出
     */
    public static String calculateAndFormatDistance(
            String lat1Str, String lon1Str,
            String lat2Str, String lon2Str) {

        try {
            double lat1 = Double.parseDouble(lat1Str);
            double lon1 = Double.parseDouble(lon1Str);
            double lat2 = Double.parseDouble(lat2Str);
            double lon2 = Double.parseDouble(lon2Str);

            // 计算距离（单位：米）
            long distanceInMeters = haversineDistance(lat1, lon1, lat2, lon2);

            // 格式化输出
            if (distanceInMeters < 1000) {
                return distanceInMeters + " 米";
            } else {
                // 转为千米，保留一位小数
                double distanceInKm = distanceInMeters / 1000.0;
                return String.format("%.1f km", distanceInKm);
            }

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("经纬度格式不正确，请检查输入值", e);
        }
    }

    /**
     * Haversine 公式计算两点间球面距离（单位：米）
     */
    private static long haversineDistance(double lat1, double lon1, double lat2, double lon2) {
        final double R = 6371000; // 地球半径，单位：米

        double latRad1 = Math.toRadians(lat1);
        double latRad2 = Math.toRadians(lat2);
        double deltaLat = Math.toRadians(lat2 - lat1);
        double deltaLon = Math.toRadians(lon2 - lon1);

        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                Math.cos(latRad1) * Math.cos(latRad2) *
                        Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return Math.round(R * c); // 返回四舍五入后的米数
    }
}
